package com.example.ibsp_demo.controller.message;

import com.example.ibsp_demo.mapper.message.PrivateMessageMapper;
import com.example.ibsp_demo.mapper.message.PrivateSessionMapper;
import com.example.ibsp_demo.mapper.user.UserMapper;
import com.example.ibsp_demo.pojo.dto.message.PrivateMessageRequest;
import com.example.ibsp_demo.pojo.entity.message.*;
import com.example.ibsp_demo.pojo.entity.user.NotificationSetting;
import com.example.ibsp_demo.pojo.entity.user.User;
import com.example.ibsp_demo.pojo.response.ResponseMessage;
import com.example.ibsp_demo.service.impl.MessageService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.boot.autoconfigure.couchbase.CouchbaseProperties;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/v1/message")
public class MessageController {

    private final MessageService messageService;
    private final PrivateMessageMapper privateMessageMapper;
    private final PrivateSessionMapper privateSessionMapper;
    private final UserMapper userMapper;
    // 注入 UserMapper
    @Autowired
    public MessageController(MessageService messageService, UserMapper userMapper, PrivateMessageMapper privateMessageMapper ,PrivateSessionMapper privateSessionMapper) {
        this.messageService = messageService;
        this.privateSessionMapper = privateSessionMapper;
        this.privateMessageMapper = privateMessageMapper;
        this.userMapper = userMapper;
    }
    // 1. 获取点赞消息列表（关联 t_like + 用户表）
    @GetMapping("/likes")
    public ResponseMessage<List<LikeMessage>> getLikeMessages(@RequestParam int userId) {
        List<LikeMessage> messages = messageService.getLikeMessages(userId);
        return ResponseMessage.success(messages);
    }

    // 2. 获取评论消息列表（关联 t_comment + 用户表）
    @GetMapping("/comments")
    public ResponseMessage<List<CommentMessage>> getCommentMessages(@RequestParam int userId) {
        List<CommentMessage> messages = messageService.getCommentMessages(userId);
        return ResponseMessage.success(messages);
    }

    // 3. 获取私信会话列表
    @GetMapping("/private/sessions")
    public ResponseMessage<List<PrivateSession>> getPrivateSessions(@RequestParam int userId) {
        List<PrivateSession> sessions = messageService.getPrivateSessions(userId);
        return ResponseMessage.success(sessions);
    }


    // 4. 获取私信详情（带分页 + 权限校验）
    // 获取私信详情（根据 sessionId）
    @GetMapping("/private/messages")
    public ResponseMessage<List<PrivateMessage>> getPrivateMessages(
            @RequestParam int sessionId,
            @RequestParam int page,
            @RequestParam int size,
            @RequestParam int userId) {

        // 校验用户是否在会话中
        if (!messageService.isUserInSession(sessionId, userId)) {
            return ResponseMessage.error(500, "无权访问该会话");
        }

        List<PrivateMessage> messages = messageService.getPrivateMessagesBySessionId(sessionId, page, size);

        // 标记为已读
        messageService.markAllReadBySessionId(sessionId, userId);

        return ResponseMessage.success(messages);
    }

    // 5. 发送私信（使用 DTO 接收请求体）
    @PostMapping("/private/send")
    public ResponseMessage<Boolean> sendPrivateMessage(
            @RequestBody PrivateMessageRequest request,
            @RequestParam int userId) {

        // 检查会话是否已存在
        if (messageService.sessionExists(userId, request.getReceiverId())) {
            System.out.println("会话已存在，直接发送消息");
        }

        boolean result = messageService.sendPrivateMessage(
                userId,
                request.getReceiverId(),
                request.getContent());
        return ResponseMessage.success(result);
    }

    // 6. 删除私信
    @DeleteMapping("/private/delete")
    public ResponseMessage<Boolean> deletePrivateMessage(@RequestParam int messageId) {
        boolean result = messageService.deletePrivateMessage(messageId);
        return ResponseMessage.success(result);
    }

    // 8. 删除私信会话（包括所有消息）
    @DeleteMapping("/private/session/{sessionId}")
    public ResponseMessage<Boolean> deletePrivateSession(@PathVariable int sessionId,@RequestParam int userId) {


        // 检查用户是否有权限删除该会话
        if (!messageService.isUserInSession(sessionId, userId)) {
            return ResponseMessage.error(500,"无权操作该会话");
        }

        boolean result = messageService.deletePrivateSession(sessionId);
        return ResponseMessage.success(result);
    }


    // 7. 获取关注提醒列表（关联 follow_relation + 用户表）
    @GetMapping("/follow-notifications")
    public ResponseMessage<List<FollowNotification>> getFollowNotifications(@RequestParam int userId) {
        List<FollowNotification> notifications = messageService.getFollowNotifications(userId);
        return ResponseMessage.success(notifications);
    }

    // 8. 执行回关操作
    @PostMapping("/follow-back")
    public ResponseMessage<Boolean> followBack(
            @RequestParam int followerId,
            @RequestParam int followedId) {
        boolean result = messageService.followBack(followerId, followedId);
        return ResponseMessage.success(result);
    }

    // 9. 获取通知设置
    @GetMapping("/notification-settings")
    public ResponseMessage<NotificationSetting> getNotificationSettings(@RequestParam int userId) {
        NotificationSetting settings = messageService.getNotificationSettings(userId);
        return ResponseMessage.success(settings);
    }

    // 10. 更新通知设置
    @PutMapping("/notification-settings")
    public ResponseMessage<Boolean> updateNotificationSettings(
            @RequestBody NotificationSetting setting) {
        boolean result = messageService.updateNotificationSettings(setting);
        return ResponseMessage.success(result);
    }

    // 11. 获取活动通知
    @GetMapping("/activity-notifications")
    public ResponseMessage<List<ActivityNotification>> getActivityNotifications(@RequestParam int userId) {
        List<ActivityNotification> notifications = messageService.getActivityNotifications(userId);
        return ResponseMessage.success(notifications);
    }
}